--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--[[

    技能环界面

]]--
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--- 界面组件
    local Widget = require "widgets/widget"
    local Image = require "widgets/image" -- 引入image控件
    local UIAnim = require "widgets/uianim"
    local Screen = require "widgets/screen"
    local AnimButton = require "widgets/animbutton"
    local ImageButton = require "widgets/imagebutton"
    local Menu = require "widgets/menu"
    local Text = require "widgets/text"
    local TEMPLATES = require "widgets/redux/templates"
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
---
    local atlas = "images/widgets/loramia_spell_ring.xml"
    local icon_atlas = "images/widgets/loramia_spell_ring_icons.xml"
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--- 技能名和图标
    local LANGUAGE = "ch"
    if type(TUNING["loramia.Language"]) == "function" then
        LANGUAGE = TUNING["loramia.Language"]()
    elseif type(TUNING["loramia.Language"]) == "string" then
        LANGUAGE = TUNING["loramia.Language"]
    end
    local spell_names_and_icon_data = {
        ["宇宙之翼"] = {"Wing Of The Universe",icon_atlas,"wings_of_universe.tex"},
        ["创造物冲击"] = {"Creation Impact",icon_atlas,"creation_impact.tex"},
        ["生命量产"] = {"Life Mass Production",icon_atlas,"life_mass_production.tex"},
        ["节能模式"] = {"Energy Saving Mode",icon_atlas,"energy_saving_mode.tex"},
    }
    local function GetSpellNameAndIconData(spell_name)
        if spell_names_and_icon_data[spell_name] then
            local ret_name = nil
            if LANGUAGE == "ch" then
                ret_name = spell_name
            else
                ret_name = spell_names_and_icon_data[spell_name][1]
            end
            return ret_name,spell_names_and_icon_data[spell_name][2],spell_names_and_icon_data[spell_name][3]
        end
        return nil,nil,nil
    end
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
---
    local function Open_Spell_Ring(inst)
        if inst.___test_fn then
            inst.___test_fn(inst)
            return
        end
        ------------------------------------------------------------------------------------------------------
        --- 前置准备
            if TheInput == nil then
                return
            end
            local front_root = inst.HUD
        ------------------------------------------------------------------------------------------------------
        --- 根节点创建
            if front_root.loramia_spell_ring_hud then   --- 杀掉重复的节点。重复点击则关闭界面
                front_root.loramia_spell_ring_hud:Kill()
                front_root.loramia_spell_ring_hud = nil
                return
            end
            local root = front_root:AddChild(Widget())
            front_root.loramia_spell_ring_hud = root

            function root:CloseSpellRing() -- 关闭技能圈圈
                self:Kill()
                front_root.loramia_spell_ring_hud = nil
                -- ThePlayer.replica.loramia_com_rpc_event:PushEvent("loramia_event.spell_ring_closed")
            end
        ------------------------------------------------------------------------------------------------------
        --- 根节点参数
            -- root:SetHAnchor(0) -- 设置原点x坐标位置，0、1、2分别对应屏幕中、左、右
            -- root:SetVAnchor(0) -- 设置原点y坐标位置，0、1、2分别对应屏幕中、上、下
            root:SetHAnchor(1) -- 设置原点x坐标位置，0、1、2分别对应屏幕中、左、右
            root:SetVAnchor(2) -- 设置原点y坐标位置，0、1、2分别对应屏幕中、上、下
            root:SetScaleMode(SCALEMODE_FIXEDSCREEN_NONDYNAMIC)   --- 缩放模式
            local MainScale = 0.6
            local temp_scale = MainScale * 0.8
            local temp_scale_delta = 0.01
        ------------------------------------------------------------------------------------------------------
        --- 按钮盒子
            local button_box = root:AddChild(Widget())
            button_box:SetPosition(0,0,0)
            button_box:SetScale(MainScale,MainScale,MainScale)
        ------------------------------------------------------------------------------------------------------
        --- 透明度
            button_box:SetCanFadeAlpha(true)
            local max_alpha = 1
            local temp_alpha = 0.1
            local temp_alpha_delta = 0.02
            button_box:SetFadeAlpha(temp_alpha)
        ------------------------------------------------------------------------------------------------------
        --- 坐标跟随 角色中心修正
            local function root_position_update_fn()
                local s_pt_x,s_pt_y= TheSim:GetScreenPos(ThePlayer.Transform:GetWorldPosition()) -- 左下角为原点。
                -- print("player in screen",s_pt_x,s_pt_y)
                root:SetPosition(s_pt_x,s_pt_y+60,0)
                --- 缩放动画
                if temp_scale < MainScale then
                    temp_scale = math.clamp(temp_scale+temp_scale_delta,0.3,MainScale)
                    button_box:SetScale(temp_scale,temp_scale,temp_scale)
                end
                --- 透明度渐变
                if temp_alpha < max_alpha then
                    temp_alpha = math.clamp(temp_alpha+temp_alpha_delta,0,max_alpha)
                    button_box:SetFadeAlpha(temp_alpha)
                end
            end
            root_position_update_fn()
            TheInput:Loramia_Add_Update_Modify_Fn(root.inst,root_position_update_fn)
        ------------------------------------------------------------------------------------------------------
        --- 按钮创建API
            local function CreateButton(image,x,y,button_custom_fn,onclick_fn)
                image = image or "empty.tex"
                local temp_button = button_box:AddChild(ImageButton(
                    atlas,image,image,image,image,image
                ))
                temp_button:SetOnClick(function()                        
                    if onclick_fn then
                        onclick_fn(temp_button)
                    end
                end)
                temp_button:SetPosition(x,y)
                ---- 遮罩
                temp_button.black_mask = temp_button.image:AddChild(Image(atlas,"black.tex"))
                temp_button.black_mask:SetScale(1.2,1.2,1.2)
                temp_button.black_mask:Hide()
                function temp_button:SetBlackMask(flag)
                    if flag then
                        self.black_mask:Show()
                    else
                        self.black_mask:Hide()
                    end
                end
                local button_scale = 128/150
                temp_button:SetScale(button_scale,button_scale,button_scale)
                --- 客制化
                if button_custom_fn then
                    button_custom_fn(temp_button)
                end
                return temp_button
            end
            local function CreateText(font,size,text,color)
                local temp_text = Text(font,size,text,color)
                function temp_text:CustomSetStr(str,x,y,ignore_regin)
                    self:SetString(str)
                    if not ignore_regin then
                        self:SetPosition(x + self:GetRegionSize()/2,y)
                    else
                        self:SetPosition(x,y)
                    end
                end
                return temp_text
            end
        ------------------------------------------------------------------------------------------------------
        --- 按钮组
            local base_x,base_y = 200,0
            local delta_x,delta_y = 60,100
            local txt_font = CODEFONT
            local txt_size = 80
            CreateButton(nil,base_x - delta_x,base_y + delta_y,function(temp_button)
                local spell_name = temp_button:AddChild(CreateText(txt_font,txt_size,"",{  255/255 , 255/255 ,255/255 , 1}))
                local spell_display_name,icon_atlas,icon_tex = GetSpellNameAndIconData("宇宙之翼")
                if spell_display_name and icon_atlas and icon_tex then
                    spell_name:CustomSetStr(spell_display_name,90,0)
                    local icon = temp_button.image:AddChild(Image(icon_atlas,icon_tex))
                else
                    spell_name:CustomSetStr("宇宙之翼",90,0)
                end
                -- local update_fn = function()
                --     local cd = ThePlayer.replica.loramia_com_spell_controller:NetGetData("test_spell")
                --     local base_str = "宇宙之翼"
                --     if type(cd) == "number" and cd > 0 then
                --         --- 强制取小数点后1位。为1的时候显示 1.0
                --         cd = string.format("%.1f",cd)
                --         base_str = base_str .. "【 " .. cd .. " 】"
                --     end
                --     spell_name:CustomSetStr(base_str,90,0)

                --     if ThePlayer.replica.loramia_com_spell_controller:IsReady("test_spell") then
                --         temp_button:SetBlackMask(false)
                --         temp_button:SetClickable(true)
                --     else
                --         temp_button:SetBlackMask(true)
                --         temp_button:SetClickable(false)
                --     end
                -- end
                -- update_fn()
                -- temp_button.inst:DoPeriodicTask(FRAMES*2,update_fn)
            end,function()
                --- 按钮点击
                -- print("BUTTON 1 ")
                ThePlayer.replica.loramia_com_rpc_event:PushEvent("loramia_event.spell_ring_selected",{
                    index = "wings_of_universe"
                })
                root:CloseSpellRing()
            end)
            CreateButton(nil,base_x,base_y,function(temp_button)
                local spell_name = temp_button:AddChild(CreateText(txt_font,txt_size,"",{  255/255 , 255/255 ,255/255 , 1}))
                local spell_display_name,icon_atlas,icon_tex = GetSpellNameAndIconData("创造物冲击")
                if spell_display_name and icon_atlas and icon_tex then
                    spell_name:CustomSetStr(spell_display_name,90,0)
                    local icon = temp_button.image:AddChild(Image(icon_atlas,icon_tex))
                else
                    spell_name:CustomSetStr("创造物冲击",90,0)
                end

                local spell_cd_time = temp_button:AddChild(CreateText(txt_font,40,"",{  255/255 , 255/255 ,255/255 , 1}))
                spell_cd_time:CustomSetStr("【 0.0 】",90,-50)
                spell_cd_time:Show()

                local spell_cost = temp_button:AddChild(CreateText(txt_font,40,"",{  255/255 , 255/255 ,255/255 , 1}))
                spell_cost:CustomSetStr("【 1.0 】",90,50)
                spell_cost:Show()

                local update_fn = function()
                    local clickable = true
                    local RECHARGE_VALUE_COST = 1   -- 充能值消耗
                    local HUNGER_VALUE_COST = 0     -- 饥饿值消耗                    

                    local cd = ThePlayer.replica.loramia_com_spell_controller:NetGetData("creation_impact")
                    if cd > 0 then
                        local cd_str = "【 " .. string.format("%.1f",cd) .. " 】"                        
                        spell_cd_time:CustomSetStr(cd_str,90,-50)
                        clickable = false
                    else
                        spell_cd_time:CustomSetStr("",90,-50)
                    end

                    local cost_str = ""
                    if ThePlayer.replica.hunger:GetCurrent() < HUNGER_VALUE_COST then
                        cost_str = cost_str .."【 B " .. HUNGER_VALUE_COST .. " 】"
                        clickable = false
                    end
                    if ThePlayer.replica.loramia_com_recharge:GetCurrent() < RECHARGE_VALUE_COST then
                        cost_str = cost_str .."【 R " .. RECHARGE_VALUE_COST .. " 】"
                        clickable = false
                    end
                    spell_cost:CustomSetStr(cost_str,90,50)

                    if clickable
                         and not ThePlayer.replica.loramia_com_spell_controller:NetGetData("energy_saving_mode")
                         and ThePlayer.replica.loramia_com_talent_tree:IsUnlocked("creation_impact")
                         then
                        temp_button:SetBlackMask(false)
                        temp_button:SetClickable(true)
                    else
                        temp_button:SetBlackMask(true)
                        temp_button:SetClickable(false)
                    end

                end
                temp_button.inst:DoPeriodicTask(FRAMES*2,update_fn)
            end,function()
                --- 按钮点击
                -- print("BUTTON 2 ")
                ThePlayer.replica.loramia_com_rpc_event:PushEvent("loramia_event.spell_ring_selected",{
                    index = "creation_impact"
                })
                root:CloseSpellRing()
            end)
            CreateButton(nil,base_x - delta_x,base_y - delta_y,function(temp_button)
                local spell_name = temp_button:AddChild(CreateText(txt_font,txt_size,"",{  255/255 , 255/255 ,255/255 , 1}))
                local spell_display_name,icon_atlas,icon_tex = GetSpellNameAndIconData("生命量产")
                if spell_display_name and icon_atlas and icon_tex then
                    spell_name:CustomSetStr(spell_display_name,90,0)
                    local icon = temp_button.image:AddChild(Image(icon_atlas,icon_tex))
                else
                    spell_name:CustomSetStr("生命量产",90,0)
                end
                local update_fn = function()
                    if ThePlayer.replica.loramia_com_talent_tree:IsUnlocked("life_mass_production") then
                        temp_button:SetBlackMask(false)
                        temp_button:SetClickable(true)
                    else
                        temp_button:SetBlackMask(true)
                        temp_button:SetClickable(false)
                    end
                end
                update_fn()
                temp_button.inst:DoPeriodicTask(FRAMES*2,update_fn)
            end,function()
                --- 按钮点击
                -- print("BUTTON 3 ")
                ThePlayer.replica.loramia_com_rpc_event:PushEvent("loramia_event.spell_ring_selected",{
                    index = "life_mass_production"
                })
                root:CloseSpellRing()
            end)
            CreateButton(nil,80,-200,function(temp_button)
                -- temp_button.image:SetRotation(30)
                local spell_name = temp_button:AddChild(CreateText(txt_font,txt_size,"",{  255/255 , 255/255 ,255/255 , 1}))
                -- spell_name:CustomSetStr("节能模式",90,0)
                local pt = Vector3(90,0,0)
                local display_name,icon_atlas,icon_tex = GetSpellNameAndIconData("节能模式")
                display_name = display_name or "节能模式"
                if icon_atlas and icon_tex then
                    local icon = temp_button.image:AddChild(Image(icon_atlas,icon_tex))
                end
                if ThePlayer.replica.loramia_com_talent_tree:IsUnlocked("energy_saving_mode") then
                    local off_str = LANGUAGE == "ch" and "【关闭】" or "[ Off ]"
                    local on_str = LANGUAGE == "ch" and "【开启】" or "[ On ]"
                    if ThePlayer.replica.loramia_com_spell_controller:NetGetData("energy_saving_mode") then
                        -- spell_name:CustomSetStr("【关闭】节能模式",pt.x,0)
                        spell_name:CustomSetStr(off_str .. display_name,pt.x,0)
                    else
                        -- spell_name:CustomSetStr("【开启】节能模式",pt.x,0)
                        spell_name:CustomSetStr(on_str .. display_name,pt.x,0)
                    end
                    temp_button:SetBlackMask(false)
                    temp_button:SetClickable(true)
                else
                    spell_name:CustomSetStr(display_name,pt.x,0)
                    temp_button:SetBlackMask(true)
                    temp_button:SetClickable(false)
                end
            end,function()
                --- 按钮点击
                ThePlayer.replica.loramia_com_rpc_event:PushEvent("loramia_event.spell_ring_selected",{
                    index = "energy_saving_mode"
                })
                root:CloseSpellRing()
            end)
        ------------------------------------------------------------------------------------------------------
        --- 鼠标右键点击关闭UI
            root.temp_mouse_handler = TheInput:AddMouseButtonHandler(function(button, down, x, y) 
                if button == MOUSEBUTTON_RIGHT and down == false then
                    root.temp_mouse_handler:Remove()
                    root.temp_mouse_handler = nil
                    root:CloseSpellRing()
                end
            end)
            root.inst:ListenForEvent("onremove",function()
                if root.temp_mouse_handler then
                    root.temp_mouse_handler:Remove()
                end
            end)
        ------------------------------------------------------------------------------------------------------
        --- 外部干涉的时候关闭
            root.inst:ListenForEvent("loramia_event.talent_tree_client_side_updated",function()
                root:CloseSpellRing()
            end,ThePlayer)
        ------------------------------------------------------------------------------------------------------
        ---
            ThePlayer.replica.loramia_com_rpc_event:PushEvent("loramia_event.spell_ring_opened")            
        ------------------------------------------------------------------------------------------------------
    end
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--- 按键监听器
    local function Add_KeyHandler(inst)
        local key_listener = TheInput:AddKeyHandler(function(key,down)
            -- print("+++++++++++",key,down)
            if down == true then
                --- 技能环打开
                if TUNING.LORAMIA_FN:IsKeyPressed(TUNING["loramia.Config"].LORAMIA_SPELL_RING_HOTKEY,key) then
                    Open_Spell_Ring(inst)
                    return
                end
                --- 创造物冲击
                if TUNING.LORAMIA_FN:IsKeyPressed(TUNING["loramia.Config"].LORAMIA_SPELL_RING_CREATION_IMPACT,key) then
                    ThePlayer.replica.loramia_com_rpc_event:PushEvent("loramia_event.spell_ring_selected",{
                        index = "creation_impact"
                    })
                    return
                end
                
            end
        end)
        inst:ListenForEvent("onremove",function()
            key_listener:Remove()
        end)
    end
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

return function(inst)
    inst:DoTaskInTime(1,function()
        if inst == ThePlayer and inst.HUD then
            Add_KeyHandler(inst)
        end
    end)
end